package com.cn.shuangzi.ad.activity;


import android.app.Activity;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.ViewGroup;

import com.bytedance.msdk.api.AdError;
import com.bytedance.msdk.api.GMAdEcpmInfo;
import com.bytedance.msdk.api.v2.GMNetworkPlatformConst;
import com.bytedance.msdk.api.v2.ad.splash.GMSplashAd;
import com.bytedance.msdk.api.v2.ad.splash.GMSplashAdListener;
import com.bytedance.msdk.api.v2.ad.splash.GMSplashAdLoadCallback;
import com.bytedance.msdk.api.v2.ad.splash.GMSplashMinWindowListener;
import com.cn.shuangzi.SZApp;
import com.cn.shuangzi.activity.SZSplashActivity;
import com.cn.shuangzi.ad.ADManager;
import com.cn.shuangzi.ad.bean.ADPlatform;
import com.cn.shuangzi.ad.bean.YlhErrorInfo;
import com.cn.shuangzi.ad.manager.AdSplashManager;
import com.cn.shuangzi.ad.manager.SplashMinWindowManager;
import com.cn.shuangzi.ad.util.ADConst;
import com.cn.shuangzi.ad.util.ADUtil;
import com.cn.shuangzi.util.SZUtil;
import com.cn.shuangzi.util.SZValidatorUtil;
import com.qq.e.ads.splash.SplashAD;

import java.lang.ref.SoftReference;
import java.util.List;

/**
 * 开屏广告Activity示例
 */
public abstract class GroMoreSplashActivity extends SZSplashActivity {


    private String mAdUnitId = "";
    private AdSplashManager mAdSplashManager;
    private GMSplashAdListener mSplashAdListener;
    private boolean isAdShown;
    private int SPLASH_SHOW_TIME_NORMAL = 1500;
    private long beginTime;
    private Handler handlerCloseSplash;
    private boolean isDealToNext = false;
    private boolean showInCurrent;
    private boolean isForceClose;
    private boolean isClickAd;
    private boolean isToMainDone;

    @Override
    public void onPreCreated() {
        showInCurrent = false;
        isForceClose = false;
        isClickAd = false;
        isToMainDone = false;
        resetSplashMinWindowManager();
        initCutDown();
    }

    public void init(boolean isShowAd) {
        init(isShowAd, 1000);
    }

    public void init(boolean isShowAd, long delayToMain) {
        SZApp.getInstance().init();
        dealAd(isShowAd, delayToMain);
    }

    public void dealAd(boolean isShowAd) {
        dealAd(isShowAd, 1000);
    }

    public void dealAd(boolean isShowAd, long delayToMain) {
        if (isShowAd) {
            autoCloseSplash();
            SZUtil.logError("设置自动关闭成功");
            fetchSplashAD();
        } else {
            SZUtil.logError("不展示广告，直接进主页");
            toMain(delayToMain);
        }
    }
    private void resetSplashMinWindowManager(){
        SplashMinWindowManager.getInstance().setSplashShown(false);
        SplashMinWindowManager.getInstance().setSupportSplashMinWindow(false);
        SplashMinWindowManager.getInstance().setMinWindowShown(false);
        SplashMinWindowManager.getInstance().setMinWindowViewPos(isShowMinWindowLeft() ? SplashMinWindowManager.LEFT : SplashMinWindowManager.RIGHT);

    }


    public void fetchSelfAD() {
        fetchSelfAD(null);
    }

    public void fetchSelfAD(ADManager.OnSplashADLoadListener onSplashADLoadListener) {
        beginTime = System.currentTimeMillis();
        ADManager.getInstance().getSelfAd(SZUtil.getChannel(this), getPackageName(), String.valueOf(SZUtil.getVersionCode(this)), onSplashADLoadListener);
    }

    private void fetchSplashAD() {

        beginTime = System.currentTimeMillis();
        mAdUnitId = getAdUnitId();

        initListener();
        initAdLoader();
        resetSplashMinWindowManager();
        ADManager.getInstance().getSplash(SZUtil.getChannel(this), getPackageName(), String.valueOf(SZUtil.getVersionCode(this)), new ADManager.OnSplashADLoadListener() {
            @Override
            public void onFetchAdSuccess(List<ADPlatform> adPlatformList) {
                if(SZValidatorUtil.isValidList(adPlatformList)) {
                    ADManager.getInstance().initGMAd();
                    if (mAdSplashManager != null) {
                        mAdSplashManager.loadSplashAd(mAdUnitId, isFullScreenMode() ? 0 : rltBottom.getHeight(),getBottomAdCodeId(),getScenarioId());
                    }
                }else{
                    toMainByDelay(false);
                }
            }

            @Override
            public void onFetchAdError() {
                toMainByDelay(false);
            }
        });

    }


    private void initCutDown() {
        txtVipSkip.setVisibility(View.GONE);
        txtVipSkip.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                try {
                    startActivity(getVipActivity());
                } catch (Exception e) {
                }
            }
        });
        txtSkip.setVisibility(View.GONE);
        txtSkip.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                toMainByDelay(true);
            }
        });
    }

    private void showCutDown() {
        try {
            if(handlerCloseSplash!=null){
                handlerCloseSplash.removeCallbacksAndMessages(null);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (txtSkip.getVisibility() == View.VISIBLE) {
            return;
        }
        if (isShowVipSkipBtn()) {
            txtVipSkip.setVisibility(View.VISIBLE);
        } else {
            txtVipSkip.setVisibility(View.GONE);
        }
        if(isHideSkipBtn()){
            txtSkip.setVisibility(View.GONE);
        }else {
            txtSkip.setVisibility(View.VISIBLE);
        }
    }

    public void autoCloseSplash() {
        //未知情况出现卡死的情况下，主动执行跳转
        try {
            if(handlerCloseSplash!=null){
                handlerCloseSplash.removeCallbacksAndMessages(null);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        handlerCloseSplash = new Handler();
        handlerCloseSplash.postDelayed(new Runnable() {
            @Override
            public void run() {
                SZUtil.logError("是否需要自动关闭："+!isAdShown);
                if (!isAdShown) {
                    if (!isFinishing()) {
                        SZUtil.logError("=====执行自动关闭=====");
                        toMain();
                    }
                }
            }
        }, getSplashCloseDelayTimeInNoAd());
    }

    private void initListener() {
        mSplashAdListener = new GMSplashAdListener() {
            @Override
            public void onAdClicked() {
                SZUtil.logError("开屏广告被点击");
                isClickAd = true;
            }

            @Override
            public void onAdShow() {
                isAdShown = true;
                if (isFullScreenMode()) {
                    rltBottom.setVisibility(View.GONE);
                } else {
                    rltBottom.setVisibility(View.VISIBLE);
                }
                showCutDown();
                ADUtil.setFirstUseAdTime();
                SZUtil.logError("开屏广告显示");
                GMAdEcpmInfo gmAdEcpmInfo = null;
                try {
                    gmAdEcpmInfo = mAdSplashManager.getSplashAd().getShowEcpm();
                    SZUtil.logError("当前开屏："+gmAdEcpmInfo);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                YlhErrorInfo ylhErrorInfo = ADManager.getInstance().getSplashErrorInfo();
                SplashAD splashAD = ADManager.getInstance().getCurrentSplashAD();
                if(gmAdEcpmInfo!=null&&ylhErrorInfo!=null&&splashAD!=null&&
                        !ADManager.getInstance().isYlhPlatform(gmAdEcpmInfo.getAdNetworkPlatformName())){
                    int ecpm = ylhErrorInfo.getPrice();
                    try {
                        if(ecpm<=0){
                            ecpm = 20 * ADConst.YUAN;
                        }
                        double preEcpm = Double.parseDouble(gmAdEcpmInfo.getPreEcpm());
                        if(preEcpm>0) {
                            ecpm = (int) (preEcpm + 1* ADConst.YUAN);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    ylhErrorInfo.setPrice(ecpm);
                    splashAD.sendLossNotification(ecpm,ylhErrorInfo.getReason(),ylhErrorInfo.getAdnId());
                    SZUtil.logError("上报优量汇开屏竞价失败："+ylhErrorInfo);
                }
                ADManager.getInstance().setCurrentSplashAD(null);
                ADManager.getInstance().setSplashErrorInfo(null);
            }

            /**
             * show失败回调。如果show时发现无可用广告（比如广告过期），会触发该回调。
             * 开发者应该结合自己的广告加载、展示流程，在该回调里进行重新加载。
             * @param adError showFail的具体原因
             */
            @Override
            public void onAdShowFail(AdError adError) {
                ADManager.getInstance().setCurrentSplashAD(null);
                ADManager.getInstance().setSplashErrorInfo(null);
                SZUtil.logError("聚合开屏加载失败：" + adError);
                // 开发者应该结合自己的广告加载、展示流程，在该回调里进行重新加载
                if (mAdSplashManager != null) {
                    mAdSplashManager.loadSplashAd(mAdUnitId, isFullScreenMode() ? 0 : rltBottom.getHeight(),getBottomAdCodeId(),getScenarioId());
                } else {
                    toNext();
                }
            }

            @Override
            public void onAdSkip() {
                SZUtil.logError("onAdSkip");
                toNext();
            }

            @Override
            public void onAdDismiss() {
                SZUtil.logError("onAdDismiss");
                toNext();
            }
        };
    }


    private void initAdLoader() {
        mAdSplashManager = new AdSplashManager(this, new GMSplashAdLoadCallback() {
            @Override
            public void onSplashAdLoadFail(AdError adError) {
                SZUtil.logError("聚合开屏加载失败 : " + adError.code + ", " + adError.message);
                // 获取本次waterfall加载中，加载失败的adn错误信息。
                if (mAdSplashManager.getSplashAd() != null) {
                    SZUtil.logError("聚合开屏加载失败数据: " + mAdSplashManager.getSplashAd().getAdLoadInfoList());
                }
                toMainByDelay(false);
            }

            @Override
            public void onSplashAdLoadSuccess() {
                SZUtil.logError("====聚合开屏加载成功====");
                mAdSplashManager.getSplashAd().showAd(splash_container);
                SplashMinWindowManager.getInstance().setSplashShown(true);
                initSplashMinWindowData(mAdSplashManager.getSplashAd(), splash_container);
                mAdSplashManager.printInfo();
            }

            // 注意：***** 开屏广告加载超时回调已废弃，统一走onSplashAdLoadFail，GroMore作为聚合不存在SplashTimeout情况。*****
            @Override
            public void onAdLoadTimeout() {
            }
        }, mSplashAdListener);
    }

    private void toNext() {
        if (!isDealToNext) {
            next();
        }
        isDealToNext = true;
    }

    private void toMainByDelay(boolean isNowSkip) {
        if (isNowSkip) {
            SZUtil.logError("=====执行立即跳转=====");
            toMain();
        } else {
            long delay = getDelayFinishTime();
            SZUtil.logError("=====执行延时跳转====="+delay);
            toMain(delay);
        }
    }

    private long getDelayFinishTime() {
        long errorTime = System.currentTimeMillis();
        long remainderTime = SPLASH_SHOW_TIME_NORMAL - (errorTime - beginTime);
        return remainderTime > 0 ? remainderTime : 0;
    }
    @Override
    public void toMain() {
        if(isToMainDone){
            return;
        }
        isToMainDone = true;
        if (showInCurrent && SplashMinWindowManager.getInstance().isSupportSplashMinWindow()) {
            return;
        }
        if (mAdSplashManager != null && splash_container != null && splash_container.getChildCount() > 0) {
            SplashMinWindowManager mSplashMinWindowManager = SplashMinWindowManager.getInstance();
            if (mSplashMinWindowManager.isSupportSplashMinWindow()) {
                mSplashMinWindowManager.setSplashInfo(mAdSplashManager.getSplashAd(), splash_container.getChildAt(0), getWindow().getDecorView());
            }
        }
        super.toMain();
    }
    //初始化小窗相关数据
    private void initSplashMinWindowData(GMSplashAd splashAd, ViewGroup splashContainer) {
        if (splashAd == null || splashContainer == null || splashContainer.getChildCount() <= 0) {
            return;
        }
        if(isForceShowTTMinWindow()) {
            SZUtil.logError("====强行开屏显示小窗===");
            if (splashAd.getShowEcpm().getAdNetworkPlatformId() == GMNetworkPlatformConst.SDK_NAME_PANGLE) {
                SplashMinWindowManager.getInstance().setSupportSplashMinWindow(true);
                return;
            }
        }
        SplashMinWindowListener mSplashMinWindowListener = new SplashMinWindowListener(this, splashAd, splashContainer.getChildAt(0), showInCurrent);
        splashAd.setMinWindowListener(mSplashMinWindowListener);
    }

    /**
     * 开屏广告小窗模式相关监听器
     */
    public class SplashMinWindowListener implements GMSplashMinWindowListener {
        private SoftReference<Activity> mActivity;
        private GMSplashAd mSplashAd; //开屏广告
        private View mSplashView; //开屏广告View
        private boolean mShowInCurrent;

        public SplashMinWindowListener(Activity activity, GMSplashAd splashAd, View splashView, boolean showInCurrent) {
            mActivity = new SoftReference<>(activity);
            mSplashAd = splashAd;
            mSplashView = splashView;
            mShowInCurrent = showInCurrent;
        }

        private void startSplashAnimationStart() {
            if (mActivity.get() == null || mSplashAd == null || mSplashView == null) {
                return;
            }
            SplashMinWindowManager splashMinWindowManager = SplashMinWindowManager.getInstance();
            ViewGroup content = mActivity.get().findViewById(android.R.id.content);

            splashMinWindowManager.showMinWindow(mSplashAd, mSplashView, content, content, new SplashMinWindowManager.AnimationCallBack() {
                @Override
                public void animationStart(int animationTime) {
                    SZUtil.logError("开屏小窗动画开始");
                }

                @Override
                public void animationEnd() {
                    SZUtil.logError("开屏小窗动画结束");
                    if (mSplashAd != null) {
                        mSplashAd.splashMinWindowAnimationFinish();
                    }
                }
            });
        }


        /**
         * 该广告支持开屏小窗模式，在这里展示开屏小窗
         */
        @Override
        public void onMinWindowStart() {
            //开始执行开屏小窗动画
            SZUtil.logError("开屏开始执行小窗动画");
            SplashMinWindowManager.getInstance().setSupportSplashMinWindow(true);
            if (mShowInCurrent) {
                SZUtil.logError("小窗动画 mShowInCurrent true");
                startSplashAnimationStart();
            } else {
                SZUtil.logError("小窗动画 mShowInCurrent false");
                toMainByDelay(true);
            }
        }

        /**
         * 开屏小窗播放结束或者手动关闭开屏小窗
         */
        @Override
        public void onMinWindowPlayFinish() {
            //sdk关闭了开屏小窗
            SZUtil.logError("开屏sdk关闭了小窗");
            if (mShowInCurrent) {
                SplashMinWindowManager.getInstance().clearSplashStaticData();
                toMainByDelay(true);
            }
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        isForceClose = true;
    }

    @Override
    protected void onResume() {
        if(isForceClose&&isClickAd){
            toMain();
        }
        super.onResume();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mAdSplashManager != null) {
            mAdSplashManager.destroy();
        }
        try {
            if (handlerCloseSplash != null) {
                handlerCloseSplash.removeCallbacksAndMessages(null);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        handlerCloseSplash = null;
    }

    protected long getSplashCloseDelayTimeInNoAd() {
        return 6000;
    }

    protected String getScenarioId() {
        return null;
    }

    public abstract String getAdUnitId();

    public abstract String getBottomAdCodeId();

    public abstract boolean isFullScreenMode();

    public abstract boolean isShowVipSkipBtn();

    public abstract Class<?> getVipActivity();

    protected abstract boolean isShowMinWindowLeft();

    protected abstract boolean isForceShowTTMinWindow();

    protected abstract boolean isHideSkipBtn();
}
